package cn.itsource.basic.config.interceptor;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.pojo.vo.LoginInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static void main(String[] args) {
        //封装数据
        AjaxResult result = AjaxResult.createError(PetConstant.LOGIN_TIME_OUT, "给劳资去登录");

        System.out.println(JSONObject.toJSONString(result));
    }

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从request请求头中获取到token
        String token = request.getHeader("token");
        //2.如果token不存在，直接返回去登录
        if (StringUtils.isBlank(token)){
            //返回什么 AjaxResult 1001  通过response返回
            //设置响应类型
            return loginOut(response);
        }

        //3.如果有，token作为key，去redis获取数据
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);

        //4.如果没有获取到，去登录
        if (loginInfo == null){
            return loginOut(response);
        }

        //5.获取到了，更新30分钟
        redisService.setStringKeyAndValue(token,loginInfo,30);

        return true;
    }

    private boolean loginOut(HttpServletResponse response) throws IOException {
        //返回什么 AjaxResult 1001  通过response返回
        //设置响应类型
        response.setContentType("application/json;charset=UTF-8");
        //封装数据
        AjaxResult result = AjaxResult.createError(PetConstant.LOGIN_TIME_OUT, "给劳资去登录");

        //响应数据回去
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(result));
        //拦截
        return false;
    }
}
